<template>
  <div class="timestamp-converter-tool">
    <div class="tool-header">
      <h1>时间戳转换</h1>
      <p>Unix时间戳与日期时间转换</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 转换主体 -->
        <el-col :span="16">
          <div class="converter-section">
            <!-- 时间戳转日期 -->
            <div class="timestamp-to-date">
              <h3>时间戳转日期</h3>
              <div class="input-group">
                <el-input
                  v-model="timestampInput"
                  placeholder="请输入Unix时间戳（秒或毫秒）"
                  size="large"
                  @input="convertTimestampToDate"
                >
                  <template #prepend>
                    <el-icon><Timer /></el-icon>
                  </template>
                  <template #append>
                    <el-button @click="useCurrentTimestamp" size="small">
                      当前时间戳
                    </el-button>
                  </template>
                </el-input>
              </div>
              
              <div class="conversion-result" v-if="dateResult">
                <h4>转换结果</h4>
                <div class="result-grid">
                  <div class="result-item">
                    <div class="result-label">标准格式</div>
                    <div class="result-value">{{ dateResult.standard }}</div>
                    <el-button @click="copyToClipboard(dateResult.standard)" size="small" type="primary">
                      复制
                    </el-button>
                  </div>
                  <div class="result-item">
                    <div class="result-label">ISO格式</div>
                    <div class="result-value">{{ dateResult.iso }}</div>
                    <el-button @click="copyToClipboard(dateResult.iso)" size="small" type="primary">
                      复制
                    </el-button>
                  </div>
                  <div class="result-item">
                    <div class="result-label">UTC格式</div>
                    <div class="result-value">{{ dateResult.utc }}</div>
                    <el-button @click="copyToClipboard(dateResult.utc)" size="small" type="primary">
                      复制
                    </el-button>
                  </div>
                  <div class="result-item">
                    <div class="result-label">相对时间</div>
                    <div class="result-value">{{ dateResult.relative }}</div>
                    <el-button @click="copyToClipboard(dateResult.relative)" size="small" type="primary">
                      复制
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 日期转时间戳 -->
            <div class="date-to-timestamp">
              <h3>日期转时间戳</h3>
              <div class="date-inputs">
                <div class="input-group">
                  <label>选择日期时间：</label>
                  <el-date-picker
                    v-model="dateInput"
                    type="datetime"
                    placeholder="选择日期时间"
                    size="large"
                    @change="convertDateToTimestamp"
                  />
                </div>
                
                <div class="input-group">
                  <label>时区：</label>
                  <el-select v-model="timezone" @change="convertDateToTimestamp" size="large">
                    <el-option label="本地时间" value="local" />
                    <el-option label="UTC时间" value="utc" />
                    <el-option label="北京时间 (UTC+8)" value="beijing" />
                    <el-option label="纽约时间 (UTC-5)" value="newyork" />
                    <el-option label="伦敦时间 (UTC+0)" value="london" />
                    <el-option label="东京时间 (UTC+9)" value="tokyo" />
                  </el-select>
                </div>
              </div>
              
              <div class="conversion-result" v-if="timestampResult">
                <h4>转换结果</h4>
                <div class="result-grid">
                  <div class="result-item">
                    <div class="result-label">秒级时间戳</div>
                    <div class="result-value">{{ timestampResult.seconds }}</div>
                    <el-button @click="copyToClipboard(timestampResult.seconds)" size="small" type="primary">
                      复制
                    </el-button>
                  </div>
                  <div class="result-item">
                    <div class="result-label">毫秒级时间戳</div>
                    <div class="result-value">{{ timestampResult.milliseconds }}</div>
                    <el-button @click="copyToClipboard(timestampResult.milliseconds)" size="small" type="primary">
                      复制
                    </el-button>
                  </div>
                  <div class="result-item">
                    <div class="result-label">微秒级时间戳</div>
                    <div class="result-value">{{ timestampResult.microseconds }}</div>
                    <el-button @click="copyToClipboard(timestampResult.microseconds)" size="small" type="primary">
                      复制
                    </el-button>
                  </div>
                  <div class="result-item">
                    <div class="result-label">纳秒级时间戳</div>
                    <div class="result-value">{{ timestampResult.nanoseconds }}</div>
                    <el-button @click="copyToClipboard(timestampResult.nanoseconds)" size="small" type="primary">
                      复制
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 时间计算 -->
            <div class="time-calculator">
              <h3>时间计算</h3>
              <div class="calculator-inputs">
                <div class="input-group">
                  <label>基准时间：</label>
                  <el-date-picker
                    v-model="baseTime"
                    type="datetime"
                    placeholder="选择基准时间"
                    size="large"
                    @change="calculateTime"
                  />
                </div>
                
                <div class="operation-group">
                  <label>操作：</label>
                  <el-select v-model="operation" @change="calculateTime" size="large">
                    <el-option label="加" value="add" />
                    <el-option label="减" value="subtract" />
                  </el-select>
                </div>
                
                <div class="amount-group">
                  <label>数量：</label>
                  <el-input-number v-model="amount" @change="calculateTime" size="large" />
                </div>
                
                <div class="unit-group">
                  <label>单位：</label>
                  <el-select v-model="unit" @change="calculateTime" size="large">
                    <el-option label="秒" value="seconds" />
                    <el-option label="分钟" value="minutes" />
                    <el-option label="小时" value="hours" />
                    <el-option label="天" value="days" />
                    <el-option label="周" value="weeks" />
                    <el-option label="月" value="months" />
                    <el-option label="年" value="years" />
                  </el-select>
                </div>
              </div>
              
              <div class="conversion-result" v-if="calculationResult">
                <h4>计算结果</h4>
                <div class="result-grid">
                  <div class="result-item">
                    <div class="result-label">结果时间</div>
                    <div class="result-value">{{ calculationResult.result }}</div>
                    <el-button @click="copyToClipboard(calculationResult.result)" size="small" type="primary">
                      复制
                    </el-button>
                  </div>
                  <div class="result-item">
                    <div class="result-label">时间戳（秒）</div>
                    <div class="result-value">{{ calculationResult.timestamp }}</div>
                    <el-button @click="copyToClipboard(calculationResult.timestamp)" size="small" type="primary">
                      复制
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 转换历史 -->
            <div class="conversion-history">
              <h3>转换历史</h3>
              <div class="history-list">
                <div 
                  v-for="(item, index) in conversionHistory" 
                  :key="index"
                  class="history-item"
                  @click="loadFromHistory(item)"
                >
                  <div class="history-type">{{ item.type }}</div>
                  <div class="history-info">
                    <span class="history-input">{{ item.input }}</span>
                    <span class="history-output">{{ item.output }}</span>
                    <span class="history-time">{{ item.time }}</span>
                  </div>
                </div>
                <div v-if="conversionHistory.length === 0" class="empty-history">
                  暂无转换历史
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 工具和说明 -->
        <el-col :span="8">
          <div class="tools-section">
            <div class="section-header">
              <h3>常用时间戳</h3>
            </div>
            
            <div class="common-timestamps">
              <div 
                v-for="ts in commonTimestamps" 
                :key="ts.timestamp"
                class="timestamp-item"
                @click="setTimestamp(ts.timestamp)"
              >
                <div class="ts-value">{{ ts.timestamp }}</div>
                <div class="ts-description">{{ ts.description }}</div>
              </div>
            </div>
          </div>
          
          <div class="help-section">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>使用说明</span>
                </div>
              </template>
              
              <div class="help-content">
                <h4>时间戳格式：</h4>
                <ul>
                  <li><strong>秒级：</strong> 10位数字，如 1640995200</li>
                  <li><strong>毫秒级：</strong> 13位数字，如 1640995200000</li>
                  <li><strong>微秒级：</strong> 16位数字</li>
                  <li><strong>纳秒级：</strong> 19位数字</li>
                </ul>
                
                <h4>支持格式：</h4>
                <ul>
                  <li><strong>标准格式：</strong> 2023-01-01 12:00:00</li>
                  <li><strong>ISO格式：</strong> 2023-01-01T12:00:00.000Z</li>
                  <li><strong>UTC格式：</strong> UTC时间显示</li>
                  <li><strong>相对时间：</strong> 几分钟前、几小时前等</li>
                </ul>
                
                <h4>注意事项：</h4>
                <div class="warning">
                  <p>⚠️ Unix时间戳从1970年1月1日开始</p>
                  <p>⚠️ 注意时区转换</p>
                  <p>⚠️ 毫秒级时间戳更精确</p>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Timer } from '@element-plus/icons-vue'

const timestampInput = ref('')
const dateResult = ref(null)
const dateInput = ref('')
const timezone = ref('local')
const timestampResult = ref(null)
const baseTime = ref('')
const operation = ref('add')
const amount = ref(1)
const unit = ref('days')
const calculationResult = ref(null)
const conversionHistory = ref([])

const commonTimestamps = [
  { timestamp: '1640995200', description: '2022-01-01 00:00:00' },
  { timestamp: '1672531200', description: '2023-01-01 00:00:00' },
  { timestamp: '1704067200', description: '2024-01-01 00:00:00' },
  { timestamp: '1609459200', description: '2021-01-01 00:00:00' },
  { timestamp: '1577836800', description: '2020-01-01 00:00:00' },
  { timestamp: '1546300800', description: '2019-01-01 00:00:00' }
]

const convertTimestampToDate = () => {
  if (!timestampInput.value.trim()) {
    dateResult.value = null
    return
  }
  
  const timestamp = parseInt(timestampInput.value.trim())
  if (isNaN(timestamp)) {
    ElMessage.error('请输入有效的时间戳')
    return
  }
  
  // 判断是秒级还是毫秒级
  let date
  if (timestamp.toString().length === 10) {
    date = new Date(timestamp * 1000)
  } else if (timestamp.toString().length === 13) {
    date = new Date(timestamp)
  } else {
    ElMessage.error('时间戳格式不正确')
    return
  }
  
  if (isNaN(date.getTime())) {
    ElMessage.error('时间戳超出有效范围')
    return
  }
  
  const now = new Date()
  const diff = now - date
  const relative = getRelativeTime(diff)
  
  dateResult.value = {
    standard: date.toLocaleString('zh-CN'),
    iso: date.toISOString(),
    utc: date.toUTCString(),
    relative: relative
  }
  
  addToHistory('时间戳转日期', timestampInput.value, dateResult.value.standard)
}

const convertDateToTimestamp = () => {
  if (!dateInput.value) {
    timestampResult.value = null
    return
  }
  
  let date = new Date(dateInput.value)
  
  // 根据时区调整
  switch (timezone.value) {
    case 'utc':
      date = new Date(date.getTime() + date.getTimezoneOffset() * 60000)
      break
    case 'beijing':
      date = new Date(date.getTime() - 8 * 60 * 60000)
      break
    case 'newyork':
      date = new Date(date.getTime() + 5 * 60 * 60000)
      break
    case 'london':
      date = new Date(date.getTime() + date.getTimezoneOffset() * 60000)
      break
    case 'tokyo':
      date = new Date(date.getTime() - 9 * 60 * 60000)
      break
  }
  
  const seconds = Math.floor(date.getTime() / 1000)
  const milliseconds = date.getTime()
  const microseconds = milliseconds * 1000
  const nanoseconds = microseconds * 1000
  
  timestampResult.value = {
    seconds: seconds.toString(),
    milliseconds: milliseconds.toString(),
    microseconds: microseconds.toString(),
    nanoseconds: nanoseconds.toString()
  }
  
  addToHistory('日期转时间戳', dateInput.value.toLocaleString(), seconds.toString())
}

const calculateTime = () => {
  if (!baseTime.value) {
    calculationResult.value = null
    return
  }
  
  let result = new Date(baseTime.value)
  const amountValue = amount.value
  
  switch (unit.value) {
    case 'seconds':
      result.setSeconds(result.getSeconds() + (operation.value === 'add' ? amountValue : -amountValue))
      break
    case 'minutes':
      result.setMinutes(result.getMinutes() + (operation.value === 'add' ? amountValue : -amountValue))
      break
    case 'hours':
      result.setHours(result.getHours() + (operation.value === 'add' ? amountValue : -amountValue))
      break
    case 'days':
      result.setDate(result.getDate() + (operation.value === 'add' ? amountValue : -amountValue))
      break
    case 'weeks':
      result.setDate(result.getDate() + (operation.value === 'add' ? amountValue * 7 : -amountValue * 7))
      break
    case 'months':
      result.setMonth(result.getMonth() + (operation.value === 'add' ? amountValue : -amountValue))
      break
    case 'years':
      result.setFullYear(result.getFullYear() + (operation.value === 'add' ? amountValue : -amountValue))
      break
  }
  
  const timestamp = Math.floor(result.getTime() / 1000)
  
  calculationResult.value = {
    result: result.toLocaleString('zh-CN'),
    timestamp: timestamp.toString()
  }
  
  addToHistory('时间计算', `${baseTime.value.toLocaleString()} ${operation.value === 'add' ? '+' : '-'} ${amountValue} ${unit.value}`, result.toLocaleString('zh-CN'))
}

const getRelativeTime = (diff) => {
  const seconds = Math.floor(diff / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)
  const days = Math.floor(hours / 24)
  const weeks = Math.floor(days / 7)
  const months = Math.floor(days / 30)
  const years = Math.floor(days / 365)
  
  if (years > 0) return `${years}年前`
  if (months > 0) return `${months}个月前`
  if (weeks > 0) return `${weeks}周前`
  if (days > 0) return `${days}天前`
  if (hours > 0) return `${hours}小时前`
  if (minutes > 0) return `${minutes}分钟前`
  return '刚刚'
}

const useCurrentTimestamp = () => {
  const now = Date.now()
  timestampInput.value = Math.floor(now / 1000).toString()
  convertTimestampToDate()
  ElMessage.success('已设置当前时间戳')
}

const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const addToHistory = (type, input, output) => {
  const historyItem = {
    type: type,
    input: input,
    output: output,
    time: new Date().toLocaleString('zh-CN')
  }
  
  conversionHistory.value.unshift(historyItem)
  
  // 限制历史记录数量
  if (conversionHistory.value.length > 20) {
    conversionHistory.value = conversionHistory.value.slice(0, 20)
  }
}

const loadFromHistory = (item) => {
  if (item.type === '时间戳转日期') {
    timestampInput.value = item.input
    convertTimestampToDate()
  } else if (item.type === '日期转时间戳') {
    // 这里需要解析日期字符串，简化处理
    ElMessage.success(`已加载：${item.input}`)
  } else if (item.type === '时间计算') {
    ElMessage.success(`已加载：${item.input}`)
  }
}

const setTimestamp = (timestamp) => {
  timestampInput.value = timestamp
  convertTimestampToDate()
  ElMessage.success(`已设置时间戳：${timestamp}`)
}
</script>

<style scoped>
.timestamp-converter-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.converter-section,
.tools-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.timestamp-to-date,
.date-to-timestamp,
.time-calculator,
.conversion-history {
  margin-bottom: 30px;
}

.timestamp-to-date h3,
.date-to-timestamp h3,
.time-calculator h3,
.conversion-history h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.3rem;
}

.input-group {
  margin-bottom: 15px;
}

.input-group label {
  display: block;
  font-weight: 500;
  color: #666;
  margin-bottom: 8px;
}

.date-inputs,
.calculator-inputs {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.operation-group,
.amount-group,
.unit-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.operation-group label,
.amount-group label,
.unit-group label {
  font-weight: 500;
  color: #666;
}

.conversion-result {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e9ecef;
}

.conversion-result h4 {
  color: #333;
  margin-bottom: 15px;
  font-size: 1.1rem;
}

.result-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.result-item {
  background: white;
  border-radius: 6px;
  padding: 15px;
  border: 1px solid #e9ecef;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.result-label {
  font-size: 0.9rem;
  color: #666;
  font-weight: 500;
}

.result-value {
  font-size: 1rem;
  color: #333;
  word-break: break-all;
  font-family: 'Courier New', monospace;
}

.history-list {
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.history-item:hover {
  background: #e9ecef;
  transform: translateY(-1px);
}

.history-type {
  font-size: 1rem;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.history-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
  font-size: 0.9rem;
  color: #666;
}

.history-input {
  color: #667eea;
  font-weight: 500;
}

.history-output {
  color: #28a745;
  font-weight: 500;
}

.history-time {
  color: #999;
}

.empty-history {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-style: italic;
}

.section-header {
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.common-timestamps {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.timestamp-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.timestamp-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.ts-value {
  font-size: 1rem;
  font-weight: bold;
  color: #667eea;
  margin-bottom: 5px;
  font-family: 'Courier New', monospace;
}

.ts-description {
  font-size: 0.9rem;
  color: #666;
}

.help-section {
  margin-top: 20px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.help-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.help-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.help-content li {
  margin-bottom: 5px;
}

.warning {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
  margin: 15px 0;
}

.warning p {
  margin: 5px 0;
  color: #856404;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .date-inputs,
  .calculator-inputs {
    grid-template-columns: 1fr;
  }
  
  .result-grid {
    grid-template-columns: 1fr;
  }
  
  .result-item {
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
  }
  
  .result-label {
    margin-bottom: 0;
  }
  
  .result-value {
    flex: 1;
    margin: 0 10px;
  }
}
</style>
